﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using SponsorshipManager.Database;
using SponsorshipManager.Domain;

namespace SponsorshipManager.BusinessLayer
{
    public class AddressDTO : IDbBasedObject
    {
        int AddressId { get; set; }
        Guid AddressGuid { get; set; }

        public enum StateEnum{Inactive,Active}

        public bool NeedsToSave { get; set; }

        public StateEnum State { get; set; }

        bool IsCurrent { get; set; }

        public string Title { get; set; }

        public string Street { get; set; }

        public string City { get; set; }

        public string Province { get; set; }

        public string Region { get; set; }

        public string ZipCode { get; set; }
        

        public bool Load() {
            
            StoredProcedure sp = DatabaseAdapter.Database.StoredProcedure();
            sp.Name = "uspGetAddress";
            sp.AddParameter("AddressId", DbType.Int32, AddressId);
            sp.Token = User.CurrentUser.Token;
            int ret = sp.Execute();
            if (ret == 1)
            {
                DataRow dr = sp.QueryResult.Rows[0];
                AddressId = (int)dr["AddressId"];
                AddressGuid = (Guid)dr["Guid"];
                State = (StateEnum)dr["state"];
                Title = dr["title"].ToString();
                Street = dr["street"].ToString();
                City = dr["city"].ToString();
                Province = dr["province"].ToString();
                Region = dr["region"].ToString();
                ZipCode = dr["zipcode"].ToString();
            }
            return ret==1;
        }

        public bool Save() {
            int ret=0;
            
            if (NeedsToSave) 
            {
                StoredProcedure sp = DatabaseAdapter.Database.StoredProcedure();
                if(AddressId==0)
                {
                    sp.Name = "uspCreateAddress";
                } else {
                    sp.Name ="uspUpdateAddress";
                    sp.AddParameter("AddressId",DbType.Int32,AddressId);
                }
                sp.AddParameter("State", DbType.Int32, State);
                sp.AddParameter("Title", DbType.String, Title);
                sp.AddParameter("Street", DbType.String, Street);
                sp.AddParameter("City", DbType.String, City);
                sp.AddParameter("Province", DbType.String, Province);
                sp.AddParameter("Region", DbType.String, Region);
                sp.Token = User.CurrentUser.Token;
                ret = sp.ExecuteNoQuery();

            }
            return ret>0;
        }


        public Domain.Address Address { get; set; }
    }
}
